<?php
class Customer{
	private $core;
	private $blog;
	private $con;
	private $table;
	
	private	$customer_id;
	public	$customer_login;
	public	$group_id;
	public	$isLoged;
	private $customer_password;
	private $customer_mail;
	private $customer_sessId;
	private $sessionName;
	
	public function __construct(&$core){
		global $core;
		$this->core 	=& $core;
		$this->blog 	=& $core->blog;
		$this->con 		=& $core->blog->con;
		$this->table	= $this->blog->prefix.'customer';
		$this->sessionName='dc_customersAuth';
	}
	
	public function init($uid){
		$strReq = 'SELECT * FROM '.$this->table.' WHERE customer_id='.$uid.' LIMIT 1';
		try{
			$rs = $this->con->select($strReq);
		}catch(Exception $e){
			$this->core->error->add($strReq.'<br/>'.$e->getMessage());
		}
		
		$this->customer_id = $uid;
		$this->customer_login = $rs->customer_login;
		$this->customer_password = $rs->customer_password;
		$this->customer_mail = $rs->customer_mail;
		$this->customer_sessId = $rs->customer_sessId;
		$this->group_id = $rs->group_id;
	}
	
	public function get_byGroup($gid){
		$strReq = 'SELECT customer_id FROM '.$this->table.' WHERE group_id='.$gid.' LIMIT 1';
		$rs = $this->con->select($strReq);
		return $rs;
	}
	
	public function get_permissions($categId=''){
		$permission = New Permission($this->core);
		return $permission->get_permission($this->group_id,$categId);
	}
	
	public function set_fields($params,$uid=''){
		if($uid!=''){
			$this->init($uid);
		}
		foreach($params as $key=>$value){
			$this->${key} = $value;
		}
	}
	
	public function create($login,$mail,$password){
		if($login=='' || $mail==''){
			$this->core->add('Le login et l\'adresse mail sont obligatoire');
			return false;
		}
		$this->customer_login	= $login;
		$this->customer_mail	= $mail;
		$this->customer_password= $password;
		$this->group_id			= 0;
		$cId 	= crypt::hmac($this->customer_password,microtime());
		
			
		$cur = $this->con->openCursor($this->table);
		$strReq1 = 'SELECT customer_login FROM '.$this->table
					.' WHERE customer_login=\''.$this->customer_login
					.'\' OR customer_mail=\''.$this->customer_mail.'\'';
		$rs1 = $this->con->select($strReq1);
		if($rs1->isEmpty()){
			$strReq2 = 'SELECT MAX(customer_id) FROM '.$this->table;
			$rs2 = $this->con->select($strReq2);
			if($password==''){
				$password = crypt::createPassword();
				$dbId	  = crypt::hmac($this->customer_password,$cId);
				//$this->send_ConfirmMail($mail,$password,$cId,$rs2->f(0)+1);
			}
			$this->uid = $rs2->f(0) + 1;
			$cur->customer_id = (integer) $this->uid; 
			$cur->customer_login = (string) $this->customer_login;
			$cur->customer_password = (string) crypt::hmac(DC_MASTER_KEY,$this->customer_password);
			$cur->customer_mail		= (string) $this->customer_mail;
			$cur->customer_sessId	= (string) $dbId;
			$cur->group_id			= (int) $this->group_id;
			$cur->insert();
		}else{
			if($rs1->customer_mail==$this->customer_mail)
				$this->core->error->add('Cette adresse mail est déjà utilisé');
			if($rs1->customer_login==$this->customer_login)
				$this->core->error->add('Ce Login est déjà utilisé');
		}
		if(!empty($password))$this->log_in($login,$this->customer_password);
	}
	
	public function delete(){
		$strReq = 'DELETE FROM '.$this->table.' WHERE customer_id='.$this->customer_id;
		$rs = $this->con->execute($strReq);
	}
	
	public function update(){
		$strReq = 'UPDATE '.$this->table.' SET ';
		if(!empty($this->customer_password))$strReq .= 'customer_password=\''.$this->customer_password.'\'';
		if(!empty($this->customer_mail))	$strReq .= ', customer_mail=\''.$this->customer_mail.'\'';
		if(!empty($this->customer_sessId))	$strReq .= ', customer_sessId=\''.$this->customer_sessId.'\'';
		if(isset($this->group_id))			$strReq .= ', group_id='.(int) $this->group_id;
		$strReq .= ' WHERE customer_id='.(int) $this->customer_id;
		try{
			$rs = $this->con->execute($strReq);
		}catch(Exception $e){
			$this->core->error->add($strReq.'<br/>'.$e->getMessage());
		}
	}
	
	
	// FONCTION DE SECURITE 	
	public function log_in($login,$password,$remember=false){
		// je laisse parler mon coté parano de la force, ca va en decourager plus d'un, mais aucun controle n'est a 100% sûr n'oubliez pas
		// ne m'en voulez pas si un hacker vous en veut personnellement et qu'il arrive quand meme a passer >:p 

		// on prépare le password communiqué pour comparaison avec le password stocké en base de données
		$hashPwd = crypt::hmac(DC_MASTER_KEY,$password);
		
		// verification dans la base de l'existance du couple login/password
		$strReq1 = 'SELECT customer_id,customer_password,customer_login,group_id FROM '.$this->table.' WHERE customer_login=\''.$login.'\' AND customer_password=\''.$hashPwd.'\';';
		$rs1 = $this->con->select($strReq1);
		
		$cId	= crypt::hmac(mt_rand(),microtime());
		$dbId	= crypt::hmac($rs1->customer_password,$cId);
				
		if(!$rs1->isEmpty()){
			$this->uid = $rs1->customer_id;
			$this->login = $rs1->customer_login;
			$this->group_id = $rs1->group_id;
			
			session_name($this->sessionName);
			session_start();
			$_SESSION['uid'] = $rs1->customer_id;
			$_SESSION['gid'] = $rs1->group_id;
			$_SESSION['cid'] = $cId;

			//on creer un tableau qui contiendra l'id de l'utilisateur en base ET le cookie id (permettra de retrouver pour quel utilisateur le cid correspond)
			// on le serialize tel quel sinon il tient pas dans le cookie
			$cookingMama = serialize(
				array(
					'uid'=>$rs1->customer_id,
					'cid'=>$cId
				)
			);
			
			if($remember){
				// on autorise la connexion par cookie que pour 30 jours
				setcookie($this->sessionName,$cookingMama,time()+60*60*24*30);
			}else{
				setcookie($this->sessionName,$cookingMama,0);
			}

			$this->con->execute('UPDATE '.$this->table.' SET customer_sessId=\''.$dbId.'\' WHERE customer_id=\''.$rs1->customer_id.'\';');
			$this->isLoged=1;
		}else{
			$this->core->error->add('Login ou mot de passe incorrect');
			$this->isLoged = 0;
		}
	}
	
	public function is_Loged(){
		if(!$this->isLoged){
			if(!empty($_COOKIE[$this->sessionName])){
				session_name($this->sessionName);
				session_start();
				$cookingMama = unserialize($_COOKIE[$this->sessionName]);
				//var_dump(array('session'=>$_SESSION['cid'],'cookie'=>$cookingMama['cid']));
				// on verifie que l'id de session est égale a l'id du cookie (limite le cas de vol de cookie durant la session)
				if( $_SESSION['cid'] == $cookingMama['cid'] && isset($_SESSION['cid']) && isset($COOKIE[$this->sessioName])){
					// on regenere le session_id (limite le vol de session_id)
					session_regenerate_id(true);
					// puis on dit ok on est logé
					$this->uid = $_SESSION['uid'];
					$this->isLoged = true;
					return true;
				}elseif(!empty($cookingMama['uid'])){
					// sinon il se peut que la personne ai demandé a être reconnue même apres une déconnexion (et donc destruction de la session)
					// on cherche donc dans la base de données un identifiant de session correspondant
					$rs = $this->con->select(
						'SELECT customer_password, customer_login, customer_sessId, group_id FROM '.$this->table
						.' WHERE customer_id=\''.$cookingMama['uid'].'\';');
					$dbId	= crypt::hmac($rs->customer_password,$cookingMama['cid']);
					
					if( $dbId==$rs->customer_sessId){
						//tout est ok alors on s'autorise a penser que c'est la bonne personne et on recreer sa session
						$_SESSION['uid'] = $cookingMama['uid'];
						$_SESSION['gid'] = $rs->group_id;
						$_SESSION['cid'] = $cId;
						
						$this->customer_login	= $rs->customer_login;
						$this->customer_id		= $cookingMama['uid'];
						$this->group_id			= $rs->group_id;
						$this->isLoged = true;
						return true;
					}else{
						//$this->logout();
						$this->isLoged = false;
						return false;
					}
				}
			}else{
				$this->gid = 0;
				$this->isLoged=true;
				return false;
			}
		}else{
			$this->isLoged=true;
			return true;
		}
	}
	
	public function logout(){
		$this->isLoged = false;
		session_name($this->sessionName);
		session_start();
		// Détruit toutes les variables de session
		$_SESSION = array();
		if (isset($_COOKIE[$this->sessionName])) {
    		setcookie($this->sessionName, '', time()-42000);
		}
		session_destroy();
	}
}
?>